package org.hdl.anima.proxy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hdl.anima.common.module.BasicModule;
import org.hdl.anima.message.CloseBackendSessionReq;
import org.hdl.anima.message.CreateBackendSessionReq;
import org.hdl.anima.transport.RemoteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author qiuhd
 * @since  2014年8月13日
 */
public class ServerProxys extends BasicModule {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ServerProxys.class) ;
	private Map<String, ServerProxy> proxyCache;
	private List<ServerProxyConfig> serverProxyConfigs;

	public ServerProxys(String moduleName) {
		super(moduleName);
		proxyCache = new HashMap<String, ServerProxy>();
	}
	
	public ServerProxy getServerProxy(String serverId) {
		return proxyCache.get(serverId);
	}
	
	@Override
	public void start() throws IllegalStateException {
		try {
			serverProxyConfigs =  ServerProxyHepler.loadFromLocal();
		} catch (Exception e) {
			throw new IllegalStateException("Failed to load from the static server proxy xml file");
		}
		
		ServerProxy proxy = null;
		for (ServerProxyConfig config : serverProxyConfigs) {
			proxy = new ServerProxyImpl(application,config);
			try {
				proxy.start();
				LOGGER.info("Success in Starting to server Proxy,Proxy id :{}",config.getId());
			} catch (RemoteException e) {
				throw new IllegalStateException("Failed to start server proxy,proxy id:" + config.getId()+",cause :" + e.getMessage(),e);
			}
			proxyCache.put(proxy.getId(), proxy);
		}
	}
	
	public void clientSessionCreated(int identity,String remoteAddress,int remotePort,String localAddress,int localPort,String clientType) {
		CreateBackendSessionReq req = new CreateBackendSessionReq(identity, remoteAddress, remotePort, localAddress, localPort,clientType);
		for (ServerProxy proxy :proxyCache.values()) {
			try {
				proxy.send(req);
			} catch (RemoteException e) {
				LOGGER.error("Failed to send create  session error!");
				//throw new IllegalStateException("Failed to send ,proxy id:" + config.getId()+",cause :" + e.getMessage(),e);
			}
		}
	}
	
	public void clientSessionClosed(int identity) {
		CloseBackendSessionReq req = new CloseBackendSessionReq(identity);
		for (ServerProxy proxy :proxyCache.values()) {
			try {
				proxy.send(req);
			} catch (RemoteException e) {
				LOGGER.error("Failed to send create  session error!");
			}
		}
	}

	@Override
	public void stop() {
		if (proxyCache != null) {
			for (ServerProxy proxy : proxyCache.values()) {
				proxy.stop();
			}
		}
	}

	@Override
	public void destroy() {
		stop();
		if (proxyCache != null) {
			proxyCache.clear();
			proxyCache = null;
		}
		
		if (serverProxyConfigs != null) {
			serverProxyConfigs.clear();
			serverProxyConfigs = null;
		}
	}
}

